/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.hadoop.hdfs.server.protocol;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableFactories;
import org.apache.hadoop.io.WritableFactory;

/**
 * A RaidTaskCommand is an instruction to a datanode
 * regarding some raid tasks. It tells the Datanode to 
 * construct some blocks and send them to given datanodes.
 * 
 * RaidTaskCommand format:
 * # of tasks
 * For each RaidTask:
 *   RaidTask 
 *      
 * When datanode receives the command, it will iterate all RaidTask
 * one by one. For each RaidTask, it reads *good* blocks from the machines,
 * and generates the target blocks. Then it sends the constructed blocks
 * to the machines provided.
 *      
 */
public class RaidTaskCommand extends DatanodeCommand {
  public RaidTask[] tasks;
  
  public RaidTaskCommand() {}
  
  public RaidTaskCommand(int action, RaidTask[] tasks) {
    super(action);
    this.tasks = tasks;
  } 
  
  /////////////////////////////////////////////////
  // Writable
  /////////////////////////////////////////////////
  static {
    WritableFactories.setFactory(RaidTaskCommand.class, 
        new WritableFactory() {
          @Override
          public Writable newInstance() {
            return new RaidTaskCommand();
          }});
  }
  
  @Override
  public void write(DataOutput out) throws IOException {
    super.write(out);
    out.writeInt(tasks.length);
    for (int i = 0; i < tasks.length; i++) {
      tasks[i].write(out);
    }
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    super.readFields(in);
    this.tasks = new RaidTask[in.readInt()];
    for (int i = 0; i < this.tasks.length; i++) {
      this.tasks[i] = new RaidTask();
      this.tasks[i].readFields(in);
    }
  }
}
